/*
 * Copyright (C) 2021 The Chinese Software International Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tonyodev.fetch2.helper;

import com.tonyodev.fetch2.Download;
import com.tonyodev.fetch2.Error;
import com.tonyodev.fetch2.FetchListener;
import com.tonyodev.fetch2.Status;
import com.tonyodev.fetch2.database.DownloadInfo;
import com.tonyodev.fetch2.downloader.FileDownloader;
import com.tonyodev.fetch2.util.Defaults;
import com.tonyodev.fetch2core.DownloadBlock;

import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * description FileDownloaderDelegate
 *
 * @author liuluming
 * @since 2021-05-25
 */
public class FileDownloaderDelegate implements FileDownloader.Delegate {
    private volatile boolean interrupted;
    private final DownloadInfoUpdater downloadInfoUpdater;
    private final FetchListener fetchListener;
    private final boolean retryOnNetworkGain;
    private final int globalAutoRetryMaxAttempts;

    public boolean getInterrupted() {
        return this.interrupted;
    }

    public void setInterrupted(boolean interrupted) {
        this.interrupted = interrupted;
    }

    /**
     * onStarted
     *
     * @param download download
     * @param downloadBlocks downloadBlocks
     * @param totalBlocks totalBlocks
     */
    public void onStarted(@NotNull Download download, @NotNull List downloadBlocks, int totalBlocks) {
        if (!this.getInterrupted()) {
            DownloadInfo downloadInfo = (DownloadInfo) download;
            downloadInfo.setStatus(Status.DOWNLOADING);
            this.downloadInfoUpdater.update(downloadInfo);
            this.fetchListener.onStarted(download, downloadBlocks, totalBlocks);
        }

    }

    /**
     * onProgress
     *
     * @param download download
     * @param etaInMilliSeconds etaInMilliSeconds
     * @param downloadedBytesPerSecond downloadedBytesPerSecond
     */
    public void onProgress(@NotNull Download download, long etaInMilliSeconds, long downloadedBytesPerSecond) {
        if (!this.getInterrupted()) {
            this.fetchListener.onProgress(download, etaInMilliSeconds, downloadedBytesPerSecond);
        }

    }

    /**
     * onError
     *
     * @param download download
     * @param error error
     * @param throwable throwable
     */
    @Override
    public void onError(Download download, Error error, Throwable throwable) {
        if (!this.getInterrupted()) {
            int maxAutoRetryAttempts = this.globalAutoRetryMaxAttempts != -1 ? this.globalAutoRetryMaxAttempts : download.getAutoRetryMaxAttempts();
            DownloadInfo downloadInfo = (DownloadInfo) download;
            if (this.retryOnNetworkGain && downloadInfo.getError() == Error.NO_NETWORK_CONNECTION) {
                downloadInfo.setStatus(Status.QUEUED);
                downloadInfo.setError(Defaults.getDefaultNoError());
                this.downloadInfoUpdater.update(downloadInfo);
                this.fetchListener.onQueued(download, true);
            } else if (download.getAutoRetryAttempts() < maxAutoRetryAttempts) {
                ((DownloadInfo) download).setAutoRetryAttempts(((DownloadInfo) download).getAutoRetryAttempts() + 1);
                downloadInfo.setStatus(Status.QUEUED);
                downloadInfo.setError(Defaults.getDefaultNoError());
                this.downloadInfoUpdater.update(downloadInfo);
                this.fetchListener.onQueued(download, true);
            } else {
                downloadInfo.setStatus(Status.FAILED);
                this.downloadInfoUpdater.update(downloadInfo);
                this.fetchListener.onError(download, error, throwable);
            }
        }

    }

    /**
     * onDownloadBlockUpdated
     *
     * @param download download
     * @param downloadBlock downloadBlock
     * @param totalBlocks totalBlocks
     */
    public void onDownloadBlockUpdated(@NotNull Download download, @NotNull DownloadBlock downloadBlock, int totalBlocks) {
        if (!this.getInterrupted()) {
            this.fetchListener.onDownloadBlockUpdated(download, downloadBlock, totalBlocks);
        }

    }

    /**
     * onComplete
     *
     * @param download download
     */
    public void onComplete(@NotNull Download download) {
        if (!this.getInterrupted()) {
            DownloadInfo downloadInfo = (DownloadInfo) download;
            downloadInfo.setStatus(Status.COMPLETED);
            this.downloadInfoUpdater.update(downloadInfo);
            this.fetchListener.onCompleted(download);
        }

    }

    /**
     * saveDownloadProgress
     *
     * @param download download
     */
    public void saveDownloadProgress(@NotNull Download download) {
        if (!this.getInterrupted()) {
            DownloadInfo downloadInfo = (DownloadInfo) download;
            downloadInfo.setStatus(Status.DOWNLOADING);
            this.downloadInfoUpdater.updateFileBytesInfoAndStatusOnly(downloadInfo);
        }

    }

    /**
     * getNewDownloadInfoInstance
     *
     * @return true
     */
    @NotNull
    public DownloadInfo getNewDownloadInfoInstance() {
        return this.downloadInfoUpdater.getNewDownloadInfoInstance();
    }

    /**
     * FileDownloaderDelegate
     *
     * @param downloadInfoUpdater downloadInfoUpdater
     * @param fetchListener fetchListener
     * @param retryOnNetworkGain retryOnNetworkGain
     * @param globalAutoRetryMaxAttempts globalAutoRetryMaxAttempts
     */
    public FileDownloaderDelegate(@NotNull DownloadInfoUpdater downloadInfoUpdater, @NotNull FetchListener fetchListener, boolean retryOnNetworkGain, int globalAutoRetryMaxAttempts) {
        super();
        this.downloadInfoUpdater = downloadInfoUpdater;
        this.fetchListener = fetchListener;
        this.retryOnNetworkGain = retryOnNetworkGain;
        this.globalAutoRetryMaxAttempts = globalAutoRetryMaxAttempts;
    }
}
